Regular Expressions (RegExp) are a specialized formal grammar used to describe, match, and manipulate patterns within string data. In JavaScript, a RegExp acts as a blueprint for the engine to perform search-and-validate operations.
1. Defining the Grammar
There are two primary ways to instantiate a pattern: the literal notation (var re2 = /abc/;), compiled when the script loads, and the RegExp constructor (var re1 = new RegExp("abc");), which allows for building patterns dynamically from variables.
2. The .test() Method
The .test() method is the most fundamental way to apply this grammar; it returns a Boolean indicating if the pattern exists anywhere within the target string. Certain characters like + have functional meanings and must be escaped with a backslash (e.g., /eighteen\+/) to be matched literally.